# apps/user_management/api/routers.py
from ninja import Router
from jose import jwt
from datetime import datetime, timedelta
from django.conf import settings
from django.contrib.auth import authenticate
from .schemas import *
from .auth import AdminAuth, DispatcherAuth
from ..models import CustomUser, UserRole
from datetime import datetime, timedelta, timezone


main_router = Router(tags=['乘客帐号管理'])

# ----------------------------
# 工具函数
# ----------------------------
def generate_jwt(user: CustomUser) -> str:
    """生成JWT令牌（包含用户角色）"""
    return jwt.encode(
        {
            "sub": str(user.id),
            "role": user.role,
            "exp": datetime.now(timezone.utc) + timedelta(hours=8)
        },
        settings.SECRET_KEY,
        algorithm="HS256"
    )

# ----------------------------
# 公共路由（无需认证）
# ----------------------------
@main_router.post("/register", response={201: UserResponse, 400: dict})
def register_user(request, payload: UserRegisterRequest):
    """普通用户注册（自动分配user角色）"""
    if CustomUser.objects.filter(email=payload.email).exists():
        return 400, {"detail": "邮箱已注册"}
    
    user = CustomUser.objects.create_user(
        email=payload.email,
        password=payload.password,
        full_name=payload.full_name,
        phone=payload.phone,
        role=UserRole.USER
    )
    return 201, UserResponse.model_validate(user)

@main_router.post("/login", response={200: TokenResponse, 401: dict})
def login(request, payload: LoginRequest):
    """所有用户登录入口"""
    user = authenticate(email=payload.email, password=payload.password)
    if not user:
        return 401, {"detail": "邮箱或密码错误"}
    
    return 200, {
        "access_token": generate_jwt(user),
        "role": user.role,
        "name": user.full_name
    }
    

# ----------------------------
# 管理员路由组（需AdminAuth权限，路径前缀为 /admin）
# ----------------------------
admin_router = Router(tags=["管理员帐号功能"])

@admin_router.post("/users", auth=AdminAuth(),response={201: UserResponse, 400: dict})
def admin_create_user(request, payload: AdminCreateUserRequest):
    """管理员创建用户（可指定角色）"""
    if CustomUser.objects.filter(email=payload.email).exists():
        return 400, {"detail": "邮箱已存在"}
    
    user = CustomUser.objects.create_user(
        email=payload.email,
        password=payload.password,
        full_name=payload.full_name,
        phone=payload.phone,
        role=payload.role
    )
    return 201, UserResponse.model_validate(user)

# ----------------------------
# 调度员路由组（需DispatcherAuth权限，路径前缀为 /dispatcher）
# ----------------------------
dispatch_router = Router(tags=["调度员帐号功能"])

@dispatch_router.get("/dashboard", auth=DispatcherAuth())
def dispatch_dashboard(request):
    """调度员仪表盘（示例接口）"""
    return {"message": "欢迎访问调度面板"}